package com.lance.answer.gui.answer.gk.answer.lms.batch.task;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.lance.answer.dto.CompleteInfo;
import com.lance.answer.gui.answer.Util;
import com.lance.answer.gui.answer.gk.answer.lms.batch.dto.LmsWatchDTO;
import com.lance.answer.gui.answer.gk.answer.lms.util.LmsUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;


@Slf4j
public class BatchCreteTopicTask extends Thread {


    public static ExecutorService pool = Executors.newSingleThreadExecutor();

    private final String driverPath;
    private final LinkedBlockingDeque<LmsWatchDTO> watchDTOS;

    public BatchCreteTopicTask(String driverPath, LinkedBlockingDeque<LmsWatchDTO> watchDTOS) {
        this.driverPath = driverPath;
        this.watchDTOS = watchDTOS;
    }

    @SneakyThrows
    @Override
    public void run() {

        while (watchDTOS.size() > 0) {
            LmsWatchDTO lmsWatchDTO = watchDTOS.take();
            String userName = lmsWatchDTO.getUsername();
            String password = lmsWatchDTO.getPassword();
            log.info("任务：{} 剩余 {} 行 用户名：{} 密码：{}",
                    Thread.currentThread().getName(), watchDTOS.size(), userName, password);
            run(driverPath, lmsWatchDTO);
        }

        if (watchDTOS.size() == 0) {
            log.info("课程所有用户均已执行完毕，系统将在20min后结束");
            TimeUnit.MINUTES.sleep(20);
            return;
        }
    }


    // 完型填空类型
    public static final String CLOZE = "subject ng-scope cloze";

    public static void run(String driverPath, LmsWatchDTO lmsWatchDTO) throws Exception {

        Map<String, Set<String>> urlMap = Maps.newHashMap();
        urlMap.put("政治经济学", Sets.newHashSet("https://lms.ouchn.cn/course/10000001741/learning-activity/full-screen#/10000208262"));


        String userName = lmsWatchDTO.getUsername();
        String pwd = lmsWatchDTO.getPassword();
        String courseName = lmsWatchDTO.getCourseName();

        Set<String> urlTasks = urlMap.get(courseName);


        String completeInfoFilePath = "libs//lmsAnswerInfo//" + courseName + "//" + userName + "-topic.txt";



        ChromeDriver driver = Util.getDriver(driverPath);
        try {
            String url = "https://menhu.pt.ouchn.cn/site/ouchnPc/index";
            driver.get(url);
            Thread.sleep(3000);


            //  pool.submit(() -> LmsUtil.login(driver, userName, pwd));
            LmsUtil.login(driver, userName, pwd);

            TimeUnit.SECONDS.sleep(5);

            // 要求分数 FIXME 每个课程要求的分数不一样

            log.info("开始答题.........{}", courseName);
            study(driver, courseName,urlTasks);

        } catch (Exception e) {

        } finally {
            try {
                driver.close();
                Util.switchToFirst(driver);
                driver.quit();
            } catch (Exception e1) {

            }
        }
    }


    private static void study(WebDriver driver, String subjectName,Set<String> urlTasks  )   {

        Map<String, Map<String, String>> topicMap = Maps.newHashMap();




        Map<String, String> topic = topicMap.get(subjectName);
        int i = 0;
        for (String url : urlTasks) {

            try {
                driver.get(url);
                Thread.sleep(5000);
                WebElement we = Util.findByCssSelector(driver, "a[data-label=\"发表帖子\"]");
                if (we != null) {
                    we.click();
                    Thread.sleep(1000);
                    driver.findElement(By.cssSelector("input[ng-model='topic.title']")).sendKeys("如何看待当代资本主义国家生产方式发生的变化");

                    driver.findElement(By.cssSelector("div[class='topic-form-section main-area']")).
                            findElement(By.cssSelector("div[class='simditor']")).click();
                    try {
                        driver.findElement(By.id("add-topic-popup")).findElement(By.cssSelector("div[class='simditor-body needsclick']"))
                                .sendKeys("1、生产力方面的变化\n" +
                                        "在经济发展层面上，当代资本主义特别是主要资本主义国家，生产力加速发展，劳 动生产率大幅度提高，社会 财富也迅猛增长，经济保持了较长时期的相对稳定发展。在产业结构层面上，出现 了转向信息化、服务化和高科技化的趋势。第3三产业迅速崛起，第一、 第二产业的比重 则大幅度下降。从生产力要素的新变化论述了生产力的变化。劳动者:劳动力结构变化 很大,脑力劳动者比例攀升，素质显著提高;劳动工具:发生革命性变革，由传统的“三 机系统”(动力机、工作机、传动机)发展为“四机系统\"(增加了电脑控制机);劳动对象: 人工合成材料的问世,新资源的开发利用,尤其是信息资源这一-非物质 资源的广泛应用, 从根本上改变了劳动对象的物质范围。此外，作为生产力重要组成部分的生产管理，由 于电子计算机、信息技术、控制论、系统工程等的运用，而获得了新的手段和工具。\n" +
                                        "2.生产关系方面的变化\n" +
                                        "从四个方面阐述了当代资本主义生产关系的变化:政府对微观经济和宏观 经济进行干预:推行雇员持股计划;实行福利政策;用税收调节收入再分配。庞仁芝认 为，生产关系的变化，首先表现为国家垄断资本主义的发展:国家与私人垄断资本相结 合;发展资本主义国有企业;国家干预、管理和调节经济生活各个方面。");
                    } catch (Exception e) {

                    }
                    Thread.sleep(2000);
                    for (WebElement saveWe : driver.findElement(By.id("add-topic-popup")).findElements(By.cssSelector("button[class='button button-green medium']"))) {
                        if ("保存".equals(saveWe.getText())) {
                            saveWe.click();
                            Thread.sleep(2000);
                            break;
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }


        }
        try {
            driver.close();
            driver.quit();
        } catch (Exception e1) {

        }
    }


}
